<template>
	<view class="payment-container">
		<!-- 加载中提示 -->
		<view class="loading" v-if="loading">
			<uni-loading-icon size="24" color="#f44"></uni-loading-icon>
			<text class="loading-text">正在跳转到支付宝支付...</text>
		</view>

		<!-- 支付失败提示 -->
		<view class="fail-container" v-else-if="payFail">
			<uni-icons type="close-circle" size="48" color="#f44"></uni-icons>
			<text class="fail-text">{{ failMsg }}</text>
			<button class="back-btn" @click="goBack">返回订单列表</button>
		</view>
		<web-view v-if="showWebView" :html="alipayHtml" @loaded="onWebViewLoaded"></web-view>
	</view>
</template>

<script>
	import orderApi from '@/api/order/order'
	export default {
		data() {
			return {
				loading: true,
				payFail: false,
				failMsg: '',
				orderId: '', // 从create.vue传递的订单ID
				totalAmount: 0 // 订单总金额
			}
		},
		onLoad(options) {
			// 接收create.vue传递的参数
			this.orderId = Number(options.orderId)
			this.totalAmount = Number(options.totalAmount)
			// 初始化支付（调用后端生成支付宝页面）
			this.initPayment()
		},
		methods: {
			async initPayment() {
				try {
					const res = await orderApi.getAlipayPage({
						orderId: this.orderId,
						totalAmount: this.totalAmount,
						returnUrl: encodeURIComponent('http://127.0.0.1:8081/#/pages/order/detail?orderId=' +
							this.orderId)
					})

					if (res.code === 200) {
						this.loading = false
						this.alipayHtml = res.data // 存储表单HTML
						this.showWebView = true // 显示web-view
					} else {
						// 原有失败逻辑
					}
				} catch (error) {
					// 原有异常逻辑
				}
			},
			// 监听web-view加载完成，再提交表单（避免DOM未就绪）
			onWebViewLoaded() {
				// 延迟100ms确保表单渲染完成（比500ms更合理，可根据实际调整）
				setTimeout(() => {
					// 查找支付宝表单（沙箱action前缀正确）
					const form = document.querySelector('form[action^="https://openapi-sandbox.dl.alipaydev.com"]')
					if (form) {
						form.submit() // 提交表单跳转到支付宝沙箱
					} else {
						this.payFail = true
						this.failMsg = '未找到支付表单，请重试'
						this.showWebView = false
					}
				}, 100)
			},
			// 返回订单列表
			goBack() {
				uni.navigateTo({
					url: '/pages/order/list'
				})
			}
		}
	}
</script>

<style lang="scss">
	.payment-container {
		width: 100vw;
		height: 100vh;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: #fff;
	}

	.loading {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 20rpx;

		.loading-text {
			font-size: 28rpx;
			color: #666;
		}
	}

	.fail-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 30rpx;
		padding: 0 40rpx;

		.fail-text {
			font-size: 28rpx;
			color: #f44;
			text-align: center;
		}

		.back-btn {
			width: 60%;
			height: 80rpx;
			line-height: 80rpx;
			background-color: #f44;
			color: #fff;
			border-radius: 40rpx;
			font-size: 28rpx;
			margin-top: 20rpx;
		}
	}
</style>